const path = require('path');
const webpack = require('webpack');
// Glob 是一种用来匹配路径与文件的模式。
const glob = require('glob');
// 提取到单独的css文件
const ExtractTextPlugin = require("extract-text-webpack-plugin");
// 简化了HTML文件的创建
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 清理./dist文件夹
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;

const entries = getEntry('src/js/page/**/*.js', 'src/js/page/');
const chunks = Object.keys(entries);

const config = {
  entry: entries,
  output: {
    path: path.resolve(__dirname, '../dist'),
    // publicPath: '/dist/',
    filename: 'js/[name].js',
    chunkFilename: 'js/[id].chunk.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: "css-loader"
        })
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
            loader: 'babel-loader',
            options: {
              presets: ['babel-preset-env']
            }
        }
      },
      {
        test: require.resolve('zepto'),
        use: ['exports-loader?window.Zepto','script-loader']
      }
    ]
  },
  plugins: [
    // 自动加载模块
    new webpack.ProvidePlugin({
        $: 'zepto'
    }),
    new CleanWebpackPlugin(['dist']),
    new CommonsChunkPlugin({
        name: 'vendors',
        chunks: chunks,
        minChunks: chunks.length
    }),
    new ExtractTextPlugin('css/[name].css')
  ]
};

module.exports = config;

const pages = Object.keys(getEntry('src/view/**/*.html', 'src/view/'));
pages.forEach((pathname)=>{
    let conf = {
        filename: 'view/' + pathname + '.html', //生成的html存放路径，相对于path
        template: 'src/view/' + pathname + '.html', //html模板路径
        inject: false
    };
    if(pathname in entries){
        // conf.favicon = 'src/imgs/favicon.ico';
        conf.inject = 'body';
        conf.chunks = ['vendors', pathname];
        conf.hash = true;
    }
    config.plugins.push(new HtmlWebpackPlugin(conf));
});

function getEntry(globPath, pathDir) {
    var files = glob.sync(globPath);
    var entries = {},
        entry, dirname, basename, pathname, extname;

    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);
        extname = path.extname(entry);
        basename = path.basename(entry, extname);
        pathname = path.join(dirname, basename);
        pathname = pathDir ? pathname.replace(new RegExp('^' + pathDir), '') : pathname;
        entries[basename] = ['./' + entry];
    }
    return entries;
}